<?php
/**
 * 数据库连接管理器
 * @author wudi
 *
 */
class doom_model_mysqlconnmgr {

    static public $error;
    
    public static $connections = array();

    static public function _static_construct() {
        self::$error = new doom_core_error();
    }
    
    /**
     * 取数据库连接
     * @param array $config
     *      array('host' => 'localhost', 
                  'username' => 'root', 
                  'password' => '111111', 
                  'database' => 'cntv_uc', 
                  'charset' => 'UTF8')
     */
    static public function get($config) {

        $connKey = self::config2connKey($config);
        $conn = self::$connections[$connKey];
        if ($conn == NULL) {
            if (($conn = mysql_connect($config['host'], $config['username'], $config['password'])) == FALSE || mysql_select_db($config['database'], $conn) == FALSE || ($config['charset'] && (mysql_query("SET NAMES {$config['charset']}", $conn) == FALSE))) {
                self::$error->set(mysql_errno() , mysql_error());
                return FALSE;
            }
            self::$connections[$connKey] = $conn;
        
        }
        return $conn;
    }

    /**
     * 关闭数据库连接
     * @param array/resource $conn 数据库配置/连接resource
     */
    static public function close($conn) {

        if (is_array($conn)) {
            $config = $conn;
            $connKey = self::config2connKey($config);
            if (($conn = self::$connections[$connKey]) != NULL && is_resource($conn)) {
                
                if (mysql_close($conn)) {
                    unset(self::$connections[$connKey]);
                    return TRUE;
                } else {
                    return FALSE;
                }
            } else {
                return TRUE;
            }
        } else if (is_resource($conn)) {
            $connKey = array_search($conn, self::$connections);
            if (mysql_close($conn)) {
                unset(self::$connections[$connKey]);
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            self::$error->set(mysql_errno() , 'bad argument');
            return FALSE;
        }
    }

    /**
     * 关闭所有连接
     */
    static public function closeAll() {

        foreach (self::$connections as $connKey => $connection) {
            if (is_resource($connection)) {
                if (mysql_close($connection)) {
                    unset(self::$connections[$connKey]);
                }
            }
        }
    }

    static private function config2connKey($config) {

        return $config['host'] . '-' . $config['database'] . '-' . $config['username'];
    }
}
